package com.zmn.oms.business.impl.messageV1.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.Lists;
import com.zmn.base.pilot.common.dto.pilot.PilotCheckQuery;
import com.zmn.base.pilot.common.enums.PilotTypeEnum;
import com.zmn.base.pilot.dubbo.interfaces.pilot.PilotRemoteService;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.consts.GlobalConsts;
import com.zmn.oms.common.constant.CompanyConsts;
import com.zmn.oms.common.constant.MessageRuleIdConsts;
import com.zmn.oms.model.dto.messageV1.SendMessageParams;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.product.OrderProduct;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.services.interfaces.product.OrderProductService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 类描述：
 *
 * @author yule
 * @date 2021/1/5 12:09
 */
@Slf4j
public abstract class AbstractBaseMessage {
    protected Logger logger = LoggerFactory.getLogger(AbstractBaseMessage.class);

    @Autowired
    protected OrderProductService orderProductService;
    @DubboReference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    protected PilotRemoteService pilotRemoteService;

    /**
     * 特殊渠道消息处理
     * @return
     */
    protected boolean specialChannel(SendMessageParams params) {
        OrderWork orderWork = params.getOrderWork();
        // 特殊服务公司处理
        // 子公司家修匠 - 服务公司无法承接线索
        boolean jxj = Objects.equals(orderWork.getCompanyId(), CompanyConsts.ZMN_JXJ_COMPANY_ID) && Objects.equals(orderWork.getManageCompanyId(), CompanyConsts.ZMN_JXJ_MANAGE_COMPANY_ID);// TODO 常量 无法承接线索
        if (jxj) {
            return true;
        }
        // 特殊渠道处理
        boolean specialChannel = Lists.newArrayList(32854, 34522).contains(orderWork.getChannelId());
        if (!specialChannel) {
            return false;
        }
        // 特殊渠道保内上门 保内完成 保内取消，不发送微信消息，且变更场景id
        Integer ruleId = params.getRuleId();
        Map<Integer, Integer> specialRuleIdMap = new HashMap<>();
        specialRuleIdMap.put(MessageRuleIdConsts.YEYX_MSG_RULEID_MASTER_VISIT_TYPE_IN, MessageRuleIdConsts.YEYX_MSG_RULEID_SPECIAL_CHANNEL_MASTER_VISIT_TYPE_IN); // 上门保内
        specialRuleIdMap.put(MessageRuleIdConsts.YEYX_MSG_RULEID_COMPLETE_TYPE_IN, MessageRuleIdConsts.YEYX_MSG_RULEID_SPECIAL_CHANNEL_COMPLETE_TYPE_IN); // 完成保内
        specialRuleIdMap.put(MessageRuleIdConsts.YEYX_MSG_RULEID_CANCEL_TYPE_IN, MessageRuleIdConsts.YEYX_MSG_RULEID_SPECIAL_CHANNEL_CANCEL_TYPE_IN); // 取消保内
        if (specialRuleIdMap.get(ruleId) != null) {
            params.setRuleId(specialRuleIdMap.get(ruleId));
            return true;
        }
        return false;
    }

    /**
     * 获取产品名称
     *
     * @param orderId
     * @return
     */
    protected OrderProduct getProduct(Long orderId) {
        // 产品信息
        List<OrderProduct> orderProducts = orderProductService.listOrderProductByOrderId(orderId);
        if (CollectionUtils.isNotEmpty(orderProducts)) {
            return orderProducts.get(0);
        }

        OrderProduct orderProduct = new OrderProduct();
        orderProduct.setProductName("产品");
        orderProduct.setShowProductName("产品");
        orderProduct.setShowCategName("分类");
        orderProduct.setCategName("分类");
        return orderProduct;
    }

    /**
     * 通用参数组装
     * @param orderWork
     * @param orderDetail
     * @return
     */
    protected Map<String, String> baseParamsMapHandle(OrderWork orderWork, OrderDetail orderDetail) {
       HashMap<String, String> smsMap = new HashMap<>();
        OrderProduct orderProduct = getProduct(orderWork.getOrderId());

        smsMap.put("order_id", String.valueOf(orderWork.getOrderId()));
        smsMap.put("product_name", orderProduct.getShowCategName());
        smsMap.put("user_telephone", orderDetail.getTelephone());
        smsMap.put("order_time", DateUtil.toString(orderWork.getReceiveTime()));
        smsMap.put("duty_time", DateUtil.toString(orderWork.getDutyTime()));

        if (StringUtils.isNotBlank(orderWork.getMasterName())) {
            smsMap.put("master_name", orderWork.getMasterName());
        }

        return smsMap;
   }

    protected String getStrEnCode(String str) {
        if (StringUtils.isBlank(str)) {
            return "";
        }
        String strEnCode = str;
        try {
            strEnCode = URLEncoder.encode(str, GlobalConsts.UTF8_ENCODING);
        } catch (Exception e) {
            log.error(e.getMessage(), e.getStackTrace());
            return strEnCode;
        }
        return strEnCode;
    }

    /**
     * 获取其他特殊参数处理
     *
     * @param remark
     * @return
     */
    protected Map<String, String> getOtherParamsMap(Long orderId, String remark) {
        if (StringUtils.isBlank(remark)) {
            return null;
        }
        Map<String, String> mapString;
        try {
            mapString = JSON.parseObject(remark, new TypeReference<HashMap<String, String>>() {
            });
        } catch (Exception e) {
            logger.info("工单号{}，解析其他参数 json={}解析异常", orderId, remark);
            logger.error(e.getMessage(), e);
            return null;
        }
        return mapString;
    }

    /**
     * 是否是三日无忧退工单
     *
     * @param orderWork
     * @return
     */
    protected boolean orderAllowRefund(OrderWork orderWork) {
        try {
            logger.info("#oms#工单={},是否是三日无忧退工单，入参：channelId: {}, cityId:{}, servCategId:{}, showCategId:{}", orderWork.getOrderId(), orderWork.getChannelId(), orderWork.getCityId(), orderWork.getServCategId(), orderWork.getShowCategId());
            PilotCheckQuery query = new PilotCheckQuery();
            query.setPilotTypeId(PilotTypeEnum.THREE_DAY_RETREAT.getId());
            query.setCategId(orderWork.getShowCategId());
            query.setServCategId(orderWork.getServCategId());
            query.setChannelId(orderWork.getChannelId());
            query.setCityId(orderWork.getCityId());
            ResponseDTO<Boolean> responseDTO = pilotRemoteService.checkPilotByQuery(query);
            logger.info("#oms#工单={},是否是三日无忧退工单，出参={}", orderWork.getOrderId(), JSON.toJSONString(responseDTO));
            if (responseDTO.isSuccess() && responseDTO.getData()) {
                return true;
            }
        } catch (Exception ex) {
            logger.error(String.format("订单号%s，获取是否是三日无忧退checkSupportByChannelIdAndCityIdAndTypeAndCategId接口异常了:%s", orderWork.getOrderId(), ex.getMessage()), ex);
            return false;
        }
        return false;
    }

    protected void setParamsDefaultIfNull(Map<String, String> params){
        // 变量为空处理
        if (!params.containsKey("pay_yesno")) {
            params.put("pay_yesno", "null");
        }
        if (!params.containsKey("meter_yesno")) {
            params.put("meter_yesno", "null");
        }
        if (!params.containsKey("late_yesno")) {
            params.put("late_yesno", "null");
        }
        if (!params.containsKey("contact_time")) {
            params.put("contact_time", "null");
        }
        if (!params.containsKey("product_name")) {
            params.put("product_name", "null");
        }
        if (!params.containsKey("public_name")) {
            params.put("public_name", "null");
        }
        if (!params.containsKey("visit_time")) {
            params.put("visit_time", "null");
        }
        if (!params.containsKey("short_link")) {
            params.put("short_link", "null");
        }
        if (!params.containsKey("remark")) {
            params.put("remark", "null");
        }
        if (!params.containsKey("time")) {
            params.put("time", "null");
        }
        if (!params.containsKey("name")) {
            params.put("name", "null");
        }
        if (!params.containsKey("life_time")) {
            params.put("life_time", "null");
        }
        if (!params.containsKey("phone_number")) {
            params.put("phone_number", "null");
        }
    }

}
